<template>
  <div class="container" >
	<!--工具栏-->
	<div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
		<el-form :inline="true" :model="filters" :size="size">
			<el-form-item label="姓名" prop="name" clearable>
				<el-input v-model="filters.name" placeholder="名称" clearable></el-input>
			</el-form-item>
           <el-form-item label="状态" prop="status">
				 <el-select v-model="filters.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
			<el-form-item label="学期" prop="termId">
				 <el-select v-model="filters.termId" placeholder="请选择" @change="termChangeTeacher">
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
      <el-form-item label="科目" prop="subjectId"  >
         <el-select v-model="filters.subjectId" placeholder="请选择" style="width: 100%;"  >
            <el-option
              v-for="item in filtersOptions"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
      <el-form-item label="班级" prop="deptName">
					<popup-tree-input
					:data="deptData"
					:props="deptTreeProps"
					:prop="filters.deptName"
					:nodeKey="''+filters.deptId"
					:currentChangeHandle="deptTreeCurrentChangeHandle">
				</popup-tree-input>
			</el-form-item>

			<el-form-item>
				<kt-button :label="$t('action.search')" perms="sys:busSports:view" type="primary" @click="findPage(null)"/>
			</el-form-item>
      <el-form-item>
				<kt-button :label="$t('action.searchTo')" perms="sys:busSports:view" type="primary" @click="findPageTo(null)"/>
			</el-form-item>
			<el-form-item>
				<kt-button :label="$t('action.add')" perms="sys:busSports:add" type="primary" @click="handleAdd" />
			</el-form-item>
      <el-form-item>
				<kt-button :label="$t('action.import')" perms="sys:busSports:import" type="primary" @click="handleImport" />
			</el-form-item>
        <el-form-item>
				<kt-button :label="$t('action.export')" perms="sys:busSports:export" type="primary" @click="handleExport" />
			</el-form-item>
            <el-form-item>
				<kt-button :label="$t('action.calculation')" perms="sys:busSports:calculation" type="primary" @click="handleCalculation" />
			</el-form-item>
            <el-form-item>
				<kt-button :label="$t('action.clear')" perms="sys:busSports:clear" type="primary" @click="handleClear" />
			</el-form-item>

		</el-form>
	</div>
	<!--表格内容栏-->
	<kt-table permsEdit="sys:busSports:edit" permsAuditStart="sys:busSports:auditstart"  permsAudit="sys:busSports:audit" permsUploadFile="sys:busSports:upload" permsView="sys:busSports:view" :showAuditB="showAuditB" :pageType="pageType" permsDelete="sys:busSports:delete" :data="pageResult" :columns="columns" @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete" >
	</kt-table>
	<!--新增编辑界面-->
	<el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="editDialogVisible" :close-on-click-modal="false">
		<el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size">
			<el-form-item label="姓名" prop="studentNum"  >
         <el-select v-model="dataForm.studentNum" placeholder="请选择" style="width: 100%;" @change="termChange">
            <el-option
              v-for="item in userOptions"
              :key="item.name"
              :label="item.nickName"
              :value="item.name">
            </el-option>
          </el-select>
			</el-form-item>
			<el-form-item label="学期" prop="termId"  >
         <el-select v-model="dataForm.termId" placeholder="请选择" style="width: 100%;"   @change="termChange">
            <el-option
              v-for="item in termOptionsSave"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
			<el-form-item label="科目" prop="subjectId"  >
         <el-select v-model="dataForm.subjectId" placeholder="请选择" style="width: 100%;"  >
            <el-option
              v-for="item in subjectOptions"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
				<el-form-item label="分数" prop="score"  >
				<el-input v-model="dataForm.score" auto-complete="off"></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>
      <!-- 导入成绩弹框，选择学期 -->
       <el-dialog
      class="login-resetPwd"
      title="导入成绩"
      :visible.sync="importDialogVisible"
      width="30%"
      s>
    <el-form :model="importInline"  ref="importInline" label-position="left" label-width="100px" class="demo-ruleForm login-container">

        <el-form-item label="学期id" prop="termId"  >
         <el-select v-model="importInline.termId" placeholder="请选择"   style="width: 100%;">
            <el-option
              v-for="item in termOptionsSave"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item>
        <el-form-item label="文件名称" class="file-line" prop="fileName">
          <el-input :readonly="true" v-model="importInline.fileName" placeholder="文件名称"></el-input>
          <el-upload
            style="display: inline-block;margin: 0 10px"
            action="string"
            :show-file-list="false"
            :http-request="uploadImgImport"
            :before-upload="beforeFirstAvatarUploadexcel"
            title="导入"
          >
            <el-button type="primary" class="tableBtn">选择文件</el-button>
          </el-upload>
        </el-form-item>

  </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="importDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="importFile">导 入</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import { format } from "@/utils/datetime"
import PopupTreeInput from "@/components/PopupTreeInput"
export default {
	components:{
			KtTable,
			KtButton,
      PopupTreeInput
	},
	data() {
		return {
			size: 'small',
      pageType: 5,
			filters: {
				name: '',
        deptId:'',
        deptName:'',
        termId:'',
        status:'',
        subjectId:'',
        subjectType:1
			},
			columns: [
				{prop:"studentNum", label:"学号", minWidth:100},
        {prop:"username", label:"姓名", minWidth:100},
        {prop:"termname", label:"学期", minWidth:100},
        {prop:"deptname", label:"班级", minWidth:100},
				{prop:"subjectName", label:"科目", minWidth:100},
				{prop:"score", label:"分数", minWidth:100},
				{prop:"scoreOrder", label:"排名", minWidth:100},
        {prop:"status", label:"状态", minWidth:100,formatter: this.statusFormat},
			],
			pageRequest: { pageNum: 1, pageSize: 8 },
			pageResult: {},

			operation: false, // true:新增, false:编辑
			editDialogVisible: false, // 新增编辑界面是否显示
			editLoading: false,
			dataFormRules: {
				label: [
					{ required: true, message: '请输入名称', trigger: 'blur' }
				]
			},
			// 新增编辑界面数据
			dataForm: {
				id: null,
				studentNum: null,
				sportsC: null,
				sportTotal: null,
				sportOrder: null,
			},
      termOptions:[],
      termOptionsSave:[],
      userOptions:[],
      subjectOptions:[],
      //保存上传文件流
      itemFile: {},
      importDialogVisible: false,
      importInline:{
        termId:null,
        fileName:null
      },
      deptData: [],
			deptTreeProps: {
				label: 'name',
				children: 'children'
			},
      showAuditB: true,
            statusOptions:[
        {id:1,name:"未提交"},
        {id:2,name:"班管退回"},
        {id:3,name:"待班管审核"},
        {id:4,name:"院管退回"},
        {id:5,name:"待院管审核"},
        {id:6,name:"审核完成"},
      ],
      filtersOptions:[],
		}
	},
	methods: {
		// 获取分页数据
		async findPage(data) {
      await  this.$api.busTerm.findCurrentTerm().then(res =>{
        if(!this.filters.termId || this.filters.termId  == ''){
          this.$set(this.filters,'termId',res.data.id)
        }
      })
			if(data !== null) {
				this.pageRequest = data.pageRequest
			}
			this.pageRequest.params = [{name:'name', value:this.filters.name},
      {name:'subjectId', value:this.filters.subjectId},
      {name:'subjectType', value:this.filters.subjectType},
      {name:'deptId', value:this.filters.deptId},
      {name:'termId', value:this.filters.termId},
      {name:'status', value:this.filters.status}
      ]
		await	this.$api.busScore.findPage(this.pageRequest).then((res) => {
      if(res.code!=500){
				this.pageResult = res.data;

			}
			}).then(data!=null?data.callback:'')
		},
    findPageTo: function (data) {
      if(data !== null) {
				this.pageRequest = data.pageRequest
			}
			this.pageRequest.params = 			this.pageRequest.params = [{name:'name', value:this.filters.name},
      {name:'subjectId', value:this.filters.subjectId},
      {name:'subjectType', value:this.filters.subjectType},
      {name:'deptId', value:this.filters.deptId},
      {name:'termId', value:this.filters.termId},
      {name:'status', value:this.filters.status}
      ]
			this.$api.busScore.findPageTo(this.pageRequest).then((res) => {
				this.pageResult = res.data
			}).then(data!=null?data.callback:'')
		},
		// 批量删除
		handleDelete: function (data) {
			this.$api.busScore.batchDelete(data.params).then(data!=null?data.callback:'')
		},
		// 显示新增界面
		handleAdd: function () {
      this.dataForm = {
				id: null,
				studentNum: null,
				sportsC: null,
				sportTotal: null,
				sportOrder: null,
			}
			this.editDialogVisible = true
			this.operation = true
      this.getCurrentTern()
		},
		// 显示编辑界面
		handleEdit: function (params) {
      if(params.row.subjectId <= 0){
          	this.$message({message: '总分不可编辑', type: 'error'})
            return
      }
			this.editDialogVisible = true
			this.operation = false
			this.dataForm = Object.assign({}, params.row)
		},
		// 编辑
		submitForm: function () {
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
						this.editLoading = true
						let params = Object.assign({}, this.dataForm)
						this.$api.busScore.save(params).then((res) => {
							if(res.code == 200) {
								this.$message({ message: '操作成功', type: 'success' })
							} else {
								this.$message({message: '操作失败, ' + res.msg, type: 'error'})
							}
							this.editLoading = false
							this.$refs['dataForm'].resetFields()
							this.editDialogVisible = false
							this.findPage(null)
						})
					})
				}
			})
		},
		// 时间格式化
      	dateFormat: function (row, column, cellValue, index){
          	return format(row[column.property])
      	},
		// 状态格式化
      	statusFormat: function (row, column, cellValue, index){
        if(row.status == 1){
          return "待提交"
        }else if(row.status == 2){
          return "班管退回"
        }else if(row.status == 3){
          return "班管审核中"
        }else if(row.status == 4){
          return "院管退回"
        }else if(row.status == 5){
          return "院管审核中"
        }else if(row.status == 6){
          return "完成"
        }
          
      	},
      getTermOptions: function (type){
        this.$api.busTerm.findOptions(type).then(res  =>{
          if(type == 0){
              this.termOptions = res.data
          }else{
            this.termOptionsSave = res.data
          }

        })
      },
      getUserOptions: function (){
        this.$api.user.findUserOptions().then(res  =>{
          this.userOptions = res.data
        })
      },
      uploadImgImport(item) {
      this.itemFile = item.file
    },
        // 导入事件
    beforeFirstAvatarUploadexcel(file) {
      let termId = this.importInline.termId
      if (!termId) {
        this.$message.error('请选择导入的学期')
      }
      const isEXECL = file.type === `application/vnd.ms-excel` || file.type === `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
      if (!isEXECL) {
        this.$message.error('请导入正确的格式')
      }
      if (termId && isEXECL) {
        this.importInline.fileName = file.name
      }
      return termId && isEXECL
    },
    handleImport(){
      this.importDialogVisible = true
    },
    importFile(){
          let formData = new FormData()
          formData.append('file', this.itemFile)
          formData.append('termId', this.importInline.termId)
          formData.append('type', 2)
          this.$api.busScore.importSports(formData).then(res => {
              this.importDialogVisible = false
              this.findPage(null)
          })
    },
    		// 获取部门列表
		findDeptTree: function () {
			this.$api.dept.findDeptTree().then((res) => {
				this.deptData = res.data
			})
		},
    // 菜单树选中
    deptTreeCurrentChangeHandle (data, node) {
        	this.filters.deptId = data.id
          this.filters.deptName = data.name
		},
    //导出
    handleExport(){
      if(this.filters.deptId == '' || this.filters.termId == ''){
        this.$message.error('请选择导出的学期和班级')
      }else{
        this.$api.busScore.exportSports(this.filters).then(data => {
              //let fileName = data.headers['content-disposition'].slice(data.headers['content-disposition'].indexOf('=') + 1)
              let fileName = (new Date()).valueOf() + '-智育.xlsx'
              //let type = data.headers[`content-type`].slice(0, data.headers[`content-type`].indexOf(';'))
              let blob = new Blob([data])
              if ('download' in document.createElement('a')) {
                // 非IE下载
                const elink = document.createElement('a')
                elink.setAttribute('download', decodeURI(fileName))
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放 URL对象
                document.body.removeChild(elink)
              } else {
                // IE10+下载
                navigator.msSaveBlob(blob, fileName)
              }
        })
      }

    },
    handleCalculation(){
      if(this.filters.deptId == '' || this.filters.termId == ''){
        this.$message.error('请选择计算的学期和班级')
      }else{
        this.$api.busScore.calculationSports(this.filters).then(data => {
              this.findPage(null)
            })
      }
    },
    handleClear(){
      if(this.filters.deptId == '' || this.filters.termId == ''){
        this.$message.error('请选择清空的学期和班级')
      }else{
        this.$api.busScore.resetSports(this.filters).then(data => {
              this.findPage(null)
            })
      }
    },
    getCurrentTern(){
      this.$api.busTerm.findCurrentTerm().then(data => {
              this.$set(this.dataForm,'termId',data.id)
            })
    },
    getSubjectOptions(params){
        this.$api.busSubject.findSubjectOptions(params).then(res =>{
          this.subjectOptions = res.data
        })
    },
    termChange(){
      if(this.dataForm.studentNum && this.dataForm.termId && this.dataForm.studentNum != '' && this.dataForm.termId != '' ){
        this.getSubjectOptions({termId:this.dataForm.termId,studentNum:this.dataForm.studentNum,subjectType:1  });
        this.$set(this.dataForm,'subjectId','')
      }
    },

    getOptions(params){
        this.$api.busSubject.findSubjectOptions(params).then(res =>{
          this.filtersOptions = res.data
        })
    },
    termChangeTeacher(v){
      if(v && v != ''){
        this.getOptions({termId:v,subjectType:1  });
        this.$set(this.filters,'subjectId','')
      }
    },
    async  findCurrentTerm(){
      await  this.$api.busTerm.findCurrentTerm().then(res =>{
        this.$set(this.filters,'termId',res.data.id)
        this.termChangeTeacher(res.data.id)
      })
    },

	},
	mounted() {
    this.findCurrentTerm()
    this.getTermOptions(0)
    this.getTermOptions(2)
    this.getUserOptions()
    this.findDeptTree()
	}
}
</script>

<style scoped>

</style>
